<?php
/**
 * Created by PhpStorm.
 * Script Name: MpQrcode.php
 * Create: 2023/1/10 16:41
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\validate;


use app\common\validate\Common;
use plugin\wechat\app\model\MpQrcode as QrcodeM;

class MpQrcode extends Common
{

    public function __construct()
    {
        parent::__construct();
        $this->rule = array_merge([
            'title'  =>  'require|max:25|checkTitleExists',
            'keyword'  =>  'require|max:40',
            'scene_str'  =>  'require|max:64|checkSceneStrExists',
            'type'  => 'require|in:0,1',
            'expire'  => 'checkExpire'
        ],
            $this->rule
        );
        $this->message = array_merge([
            'title.require' => '场景名称必须',
            'title.max'     => '场景名称不能超过25个字符',
            'title.checkTitleExists'     => '场景名称已存在',
            'keyword.require' => '关键词必须',
            'keyword.max'     => '关键词不能超过40个字符',
            'scene_str.require' => '场景值必须',
            'scene_str.max'     => '场景值不能超过64个字符',
            'scene_str.checkSceneStrExists'     => '场景值已存在',
            'type.require' => '类型非法',
            'expire.checkExpire' => '临时二维码的有效时间必须在0~2592000之间',
        ],
            $this->message
        );
    }

    /**
     * 验证expire是否合法
     * @param $value
     * @param $rule
     * @param $data
     * @return bool
     * @author: fudaoji<fdj@kuryun.cn>
     */
    protected function checkExpire($value, $rule, $data){
        if($data['type'] == 1){
            return  $value > 0 && $value < 2592000;
        }
        return true;
    }

    /**
     * 验证title是否被占用
     * @param $value
     * @param $rule
     * @param $data
     * @return bool
     * @throws \think\db\exception\DbException
     * @author: fudaoji<fdj@kuryun.cn>
     */
    protected function checkTitleExists($value, $rule, $data){
        $where = [
            ['title' ,'=', $value],
            ['mp_id' ,'=', $data['mp_id']]
        ];
        if(isset($data['id'])){
            $where[] = ['id', '<>', $data['id']];
        }
        $data = QrcodeM::where($where)->count();
        return $data ? false : true;
    }

    /**
     * 验证scene_str是否被占用
     * @param $value
     * @param $rule
     * @param $data
     * @return bool
     * @throws \think\db\exception\DbException
     * @author: fudaoji<fdj@kuryun.cn>
     */
    protected function checkSceneStrExists($value, $rule, $data){
        $where = [
            ['scene_str' ,'=', $value],
            ['mp_id' ,'=', $data['mp_id']]
        ];
        if(isset($data['id'])){
            $where[] = ['id', '<>', $data['id']];
        }

        $data = QrcodeM::where($where)->count();
        return $data ? false : true;
    }

    public function sceneAdd()
    {
        return $this->only(['title','keyword', 'scene_str', 'type', 'expire']);
    }
}